#! /bin/sh

top_srcdir="@abssrcdir@"
export top_srcdir

# The top build directory, derived from the path to this script.
top_builddir=`dirname $0`


# The full path of the test case
test_file=$1
# The base name of the test case
test_file_base=`basename $1`
# The current test number for shell based tests.
test_num=0

VALGRIND="@VALGRIND@"

## BEGIN Functions

LAST_TEST=""

#
# Run a test case and capture its standard out and standard err.
#
# Usage: run_test <utility> [<argument> ...]
#
# Example:
#
#   To run rktimes and capture all of its stdio output:
#
#     run_test rktimes -V
#
run_test() {
    LAST_TEST="test: $@"
    "$@" > ${test_file_base}_${test_num}.tmp 2>&1
}

#
# Check the output generated by a run_test() call.
#
# Usage: check_output <fail message> {Expected output on stdin}
#
# Example:
#
#   To check the output of 'rktimes -V' and print out 'Unable to get version?'
#   if the output doesn't match:
#
#     run_test rktimes -V
#     check_output "Unable to get version?" <<EOF
#     0.5
#     EOF
#
check_output() {
    cmp ${test_file_base}_${test_num}.tmp -
    if test $? -ne 0; then
	echo $LAST_TEST
	echo $1
	exit 1
    fi
    test_num=`expr ${test_num} \+ 1`
}

#
# Grep for a string in the output generated by a run_test() call.
#
# Usage: grep_output_for <string> <fail maessage>
#
# Example:
#
#   To check the output of 'cbhey -l' for 'IDL:Foobar:1.0' and print out
#   'Unable to list supported interfaces?' if it is not found:
#
#     run_test cbhey -l
#     grep_output_for "IDL:Foobar:1.0" "Unable to list supported interface?"
#
grep_output_for() {
    if grep -q $1 ${test_file_base}_${test_num}.tmp > /dev/null 2>&1; then
	:
    else
	echo "${test_file_base}_${test_num}.tmp: $2"
	exit 1
    fi
    test_num=`expr ${test_num} \+ 1`
}

on_error_fail_with() {
    if test $? -ne 0; then
	echo $1 > /dev/stderr
	exit 1
    fi
}

## END Functions


# Finally, run the test...

if test -x $1 && test `basename $1 .sh` == `basename $1`; then
    if test x"$VALGRIND" != x""; then
	valgrind -q $*
    else
	exec $*
    fi
else
    # Shell script
    shift
    . ${test_file}
fi
